package com.xuecheng.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.constants.UserConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;


//用户权限校验全局过滤器
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;


    // 权限校验
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request 和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //放行一部分url
        String path = request.getURI().getPath();
        if (path.contains("coursePub/preview") ||
                path.contains("auth/login") ||
                path.contains("basic/dictionary") ||
                path.contains("category/tree-nodes") ||
                path.contains("course/upload") ||
                path.contains("search/") ||
                path.contains("payment/wx/notify")) {
            return chain.filter(exchange);
        }
        // 获取请求头Token
        String token = request.getHeaders().getFirst("Authorization");
        //2.校验token
        Boolean aBoolean = JwtUtils.verifyToken(token);
        if (!aBoolean) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); // 返回权限不足
        }
        // 提取用户的信息
        AuthInfo authInfo = JwtUtils.getInfoFromToken(token);
        // 校验token是否过期
        if (!redisTemplate.hasKey(UserConstants.USER_ID+authInfo.getUid())){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); // 返回权限不足
        }
        // 续期
        Long expire = redisTemplate.getExpire(UserConstants.USER_ID + authInfo.getUid(), TimeUnit.MINUTES);
        if (expire<30){
            redisTemplate.expire(UserConstants.USER_ID+authInfo.getUid(),180,TimeUnit.MINUTES);
        }
        // 将用户的信息设置到requrst头
        ServerHttpRequest httpRequest = request.mutate().header("payload", JSON.toJSONString(authInfo)).build();
        //将新的request 设置到exchange
        exchange.mutate().request(httpRequest);
        // 放行
        return chain.filter(exchange);


    }


    // 过滤器执行的顺序
    @Override
    public int getOrder () {
        return -1;
    }
}
